package com.lmy.androidcustomview.view

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
import com.lmy.androidcustomview.toPx

/**
 * @author
 * @功能:Xfermode的使用
 * 离屏缓冲  这里效果想要和官方文档一样需要有一个背景层
 * @Creat 2/8/21 5:43 PM
 * @Compony 465008238@qq.com
 */


@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class XfermodeView(context: Context?, attrs: AttributeSet?) :
    View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val bounds = RectF(150f.toPx, 50f.toPx, 300f.toPx, 200f.toPx)
    private val XFERMODE = PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)

    private val circleBitmap = Bitmap.createBitmap(
        150f.toPx.toInt(),
        150f.toPx.toInt(),
        Bitmap.Config.ARGB_8888
    )
    private val squareBitmap = Bitmap.createBitmap(
        150f.toPx.toInt(),
        150f.toPx.toInt(),
        Bitmap.Config.ARGB_8888
    )

    init {
        val canvas = Canvas(circleBitmap)
        paint.color = Color.parseColor("#D81B60")
        canvas.drawOval(50f.toPx, 0f.toPx, 150f.toPx, 100f.toPx, paint)
        paint.color = Color.parseColor("#2196F3")
        canvas.setBitmap(squareBitmap)
        canvas.drawRect(0f.toPx, 50f.toPx, 100f.toPx, 150f.toPx, paint)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        setLayerType(LAYER_TYPE_NONE, null)
        val count = canvas.saveLayer(bounds, null)
        //开启离屏缓冲 先画一个圆形
        canvas.drawBitmap(circleBitmap, 150f.toPx, 50f.toPx, paint)
        paint.xfermode = XFERMODE
        canvas.drawBitmap(squareBitmap, 150f.toPx, 50f.toPx, paint)
        paint.xfermode = null
        canvas.restoreToCount(count)

    }
}